package br.com.vilababy.sigvb.dao;

import java.util.List;

 import javax.persistence.Query;

import br.com.vilababy.sigvb.SIGVBFactory;

public abstract class AbstractSIGVBDAO<T> implements ISIGVBDAO<T> {
	
	/**
     * @author Diego Patrick da Silva Santos 
     */
	protected Query query;
	protected StringBuilder consulta;
	
	@Override
	public T cadastrar(T modelo) {
		SIGVBFactory.getEM().getTransaction().begin();
		modelo = SIGVBFactory.getEM().merge(modelo);
		SIGVBFactory.getEM().getTransaction().commit();
		return modelo;
	}

	@Override
	public void alterar(T modelo) {
		SIGVBFactory.getEM().getTransaction().begin();
		SIGVBFactory.getEM().merge(modelo);
		SIGVBFactory.getEM().getTransaction().commit();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public T get(Long id, Class classe) {
		return (T) SIGVBFactory.getEM().find(classe, id);
	}
	
	@Override
	public T consultar(String consulta) {
		// CADA CLASSE FILHA DEVE IMPLEMENTAR O SEU
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> listar(String consulta) {
		if (SIGVBFactory.getEM() == null)
			SIGVBFactory.createEntityManager();
		query = SIGVBFactory.getEM().createQuery(consulta);
		return query.getResultList();
	}
	
	@Override
	public void excluir(T modelo) {
		SIGVBFactory.getEM().getTransaction().begin();
		SIGVBFactory.getEM().remove(modelo);
		SIGVBFactory.getEM().getTransaction().commit();
	}
	
	public int getQuantidadeFiltrados() {
		return 0;
	}

}